package com.ringtheweb.common.util.crypto;

import com.ringtheweb.common.util.StringUtils;

/**
 * Luhn verification
 * 
 * @author ldewavri
 * 
 */
public final class CheckLuhn {



    /**
     * Perform Luhn check
     *
     * @param number the number to check
     * @return true if valid
     */
    public static Boolean isValid(String number) {
        String digitsOnly = StringUtils.getDigitsOnly(number);
        int sum = 0;
        int digit = 0;
        int addend = 0;
        boolean timesTwo = false;

        for (int i = digitsOnly.length () - 1; i >= 0; i--) {
          digit = Integer.parseInt (digitsOnly.substring (i, i + 1));
          if (timesTwo) {
            addend = digit * 2;
            if (addend > 9) {
              addend -= 9;
            }
          }
          else {
            addend = digit;
          }
          sum += addend;
          timesTwo = !timesTwo;
        }
        int modulus = sum % 10;
        return new Boolean(modulus == 0);
      }
    

}
